package com.jfinal.bbsapp.common.kit;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import com.google.common.collect.Maps;

public class HttpUtil {
	
	public static final String UTF_8 = "UTF-8";
	public static final String[] URLS = new String[]{
			"https://www.sojson.com/open/api/weather/json.shtml"
	};

	private static final String WEATHER_URL = "http://t.weather.sojson.com/api/weather/city/";

	/**
	 * 接口调用 GET
	 */
	public static String httpURLConectionGET(String urlIndex, Map<String, Object> paraMap) {
		String result = "";
		try {
			URL url = new URL(WEATHER_URL + paraMap.get("cityCode")); // 把字符串转换为URL请求地址
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
			connection.setRequestProperty("User-agent" , "ua)");
			connection.connect();// 连接会话
			// 获取输入流
			BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			String line;
			StringBuilder sb = new StringBuilder();
			while ((line = br.readLine()) != null) {// 循环读取流
				sb.append(line);
			}
			br.close();// 关闭流
			connection.disconnect();// 断开连接
			result = sb.toString();
			System.out.println(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("失败!");
		}
		return result;
	}

	private static String getUrl(String urlIndex, Map<String, Object> paraMap) {
		String url = "";
		if(urlIndex != null)
			url = URLS[Integer.parseInt(urlIndex)];
		if(!paraMap.isEmpty()){
			for(String key : paraMap.keySet()){
					url += (url.indexOf("?") > -1 ? "&" : "?") + key + "=" + paraMap.get(key).toString();
			}
		}
		System.out.println(url);
		return url;
	}

	public static String toUTF_8(String str) throws UnsupportedEncodingException {
		return changeCharset(str, UTF_8);
	}

	public static String changeCharset(String str, String newCharset) throws UnsupportedEncodingException {
		if (str != null) {
			// 用默认字符编码解码字符串。
			byte[] bs = str.getBytes();
			// 用新的字符编码生成字符串
			return new String(bs, newCharset);
		}
		return null;
	}

	/**
	 * 接口调用 POST
	 */
	public static void httpURLConnectionPOST(String urlIndex, Map<String, Object> paraMap) {
		try {
			URL url = new URL(URLS[Integer.parseInt(urlIndex)]);

			// 将url 以 open方法返回的urlConnection 连接强转为HttpURLConnection连接
			// (标识一个url所引用的远程对象连接)
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 此时cnnection只是为一个连接对象,待连接中

			// 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)
			connection.setDoOutput(true);

			// 设置连接输入流为true
			connection.setDoInput(true);

			// 设置请求方式为post
			connection.setRequestMethod("POST");

			// post请求缓存设为false
			connection.setUseCaches(false);

			// 设置该HttpURLConnection实例是否自动执行重定向
			connection.setInstanceFollowRedirects(true);

			// 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)
			// application/x-javascript text/xml->xml数据
			// application/x-javascript->json对象
			// application/x-www-form-urlencoded->表单数据
			// ;charset=utf-8 必须要，不然妙兜那边会出现乱码【★★★★★】
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

			// 建立连接
			// (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
			connection.connect();

			// 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)
			DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());

			// 将参数输出到连接
			String param = getUrl(null, paraMap);
			dataout.writeBytes(param);

			// 输出完成后刷新并关闭流
			dataout.flush();
			dataout.close(); // 重要且易忽略步骤 (关闭流,切记!)

			// System.out.println(connection.getResponseCode());

			// 连接发起请求,处理服务器响应 (从连接获取到输入流并包装为bufferedReader)
			BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			String line;
			StringBuilder sb = new StringBuilder(); // 用来存储响应数据

			// 循环读取流,若不到结尾处
			while ((line = bf.readLine()) != null) {
				// sb.append(bf.readLine());
				sb.append(line).append(System.getProperty("line.separator"));
			}
			bf.close(); // 重要且易忽略步骤 (关闭流,切记!)
			connection.disconnect(); // 销毁连接
			System.out.println(sb.toString());

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		Map<String, Object> map = Maps.newHashMap();
		map.put("city", "郑州");
		httpURLConectionGET("0", map);
	}
	
}
